import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var BMap: any
declare var toWGS84: any
declare var toMapPoint: any
@Component({
  selector: 'sa-company-page',
  templateUrl: './company-page.component.html',
  styleUrls: ['./company-page.component.css']
})
export class CompanyPageComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      provinceId: {
        validators: {
          notEmpty: {
            message: '请选择省份'
          }
        }
      },
      cityId: {
        validators: {
          notEmpty: {
            message: '请选择城市'
          }
        }
      },
      businessType: {
        validators: {
          notEmpty: {
            message: '请选择行业类型'
          }
        }
      },
      townId: {
        validators: {
          notEmpty: {
            message: '请选择市区'
          }
        }
      },
      companyName: {
        validators: {
          notEmpty: {
            message: '请输入公司名称'
          },
          stringLength: {
            max: 30,
            message: '公司名称30字以内'
          },
          remote: {
            message: '公司名称已存在,请重新添加',
            url: config.BaseURL + 'company/validateName.html',
            data: function (validator) {
              return {
                id: validator.getFieldElements('companyName').attr('companyId')
              }
            }
          }
        }
      },
      renewalCycle: {
        validators: {
          notEmpty: {
            message: '次年续费服务周期（月）'
          }
        }
      },
      warrantyCycle: {
        validators: {
          notEmpty: {
            message: '次年续费保修周期(月)，999为终身质保'
          },
          stringLength: {
            max: 3,
            message: '次年续费保修周期(月)，999为终身质保'
          }
        }
      },
      firstRenewalCycle: {
        validators: {
          notEmpty: {
            message: '首次安装服务周期（月）'
          }
        }
      },
      firstWarrantyCycle: {
        validators: {
          notEmpty: {
            message: '首次安装保修周期(月)，999为终身质保'
          },
          stringLength: {
            max: 3,
            message: '首次安装保修周期(月)，999为终身质保'
          }
        }
      },
      tel: {
        validators: {
          digits: {
            message: '请输入数字电话'
          }
        }
      },
      radius: {
        validators: {
          notEmpty: {
            message: '请输入半径(米)'
          },
          digits: {
            message: '请输入正整数'
          },
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                if (!(/^\+?[1-9][0-9]*$/.test(value))) {
                  return {
                    valid: false,
                    message: '请输入正整数'
                  }
                } else {
                  return true;
                }
              } else {
                return {
                  valid: false,
                  message: '请输入半径(米)'
                }
              }
            }.bind(this)
          }
        }
      },
      signUnit: {
        validators: {}
      }
    }
  }
  page: any = {
    id: '',
    provinceId: '',
    cityId: '',
    townId: '',
    companyName: '',
    parentId: '',
    parentName: '',
    businessType: '',
    saleAscription: '',
    tel: '',
    address: '',
    signUnit: '',
    lng: '',
    lat: '',
    mappingCode: '',
    renewalCycle: '12',
    warrantyCycle: '12',
    remark: '',
    isEnable: 0,
    isSyncRenewal: 1,
    isSyncwarranty: 1,
    firstRenewalCycle: '12', // 首次安装的服务周期
    firstWarrantyCycle: '12', //首次安装的维修周期
    radius: 1000
  }
  areaData: any[] = [] //省市县数据
  provinceNameArr: any[] = [] //省数据
  cityNameArr: any[] = [] //城市数据
  townNameArr: any[] = [] //县数据
  businessTypeList: any[] = [] //行业类型
  companyInfo: any = {} //公司信息
  page_title: string = '新增'
  pageType: string = 'new'
  curPage: number = 0 //缓存页码使用
  rowId = null
  timer: any
  companyList: any //公司数据
  synchroParentSelect: any = false // 是否同步父级
  isOpenCycle: any = false // 是否开启续费周期
  renewChildSelect: any = false // 是否同步续费周期子集
  warrantyChildSelect: any = false // 是否同步保修周期子集
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.rowId = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
    this.businessTypeList = businessTypeList
  }
  //省份change回调事件
  provinceChange(e) {
    this.cityNameArr = []
    this.townNameArr = []
    this.page.provinceId = e
    this.page.cityId = ''
    for (let item of this.areaData) {
      if (this.page.provinceId === item.parentId) {
        this.cityNameArr.push(item)
      }
    }
  }
  //城市change回调事件
  cityChange(e) {
    this.townNameArr = []
    this.page.cityId = e
    this.page.townId = ''
    for (let item of this.areaData) {
      if (this.page.cityId === item.parentId) {
        this.townNameArr.push(item)
      }
    }
  }
  townChange(e) {
    this.page.townId = e
  }
  //行业类型选择
  businessTypeChange(e) {
    this.page.businessType = e
    this.isRequiredForSignUnit()
  }
  timeOut: any = ''
  companySelected(data) {
    $('button[type="submit"]').removeAttr('disabled')
    this.page.parentId = data.companyId || ''
    this.page.parentName = data.companyName || ''
    this.companyList = data.companyList || []

    // if (this.synchroParentSelect) {
    if (data.companyId) {
      if (this.timeOut) {
        clearTimeout(this.timeOut)
        this.timeOut = null
      }
      this.timeOut = setTimeout(async () => {
        this.getCompanyCycle(data.companyId, 1, true)
        clearTimeout(this.timeOut)
        this.timeOut = null
      }, 300)
    } else {
      this.page.renewalCycle = '12'
      this.page.warrantyCycle = '12'
    }
    // }
    this.isRequiredForSignUnit()
    this.getSignUnit(data.companyId)
    this.getSaleAscription(data.companyId)
  }
  // 根据公司id获取公司的周期
  getCompanyCycle(id = '', type, changeType?) {
    if (!id) {
      return
    }
    let reqdata = 'companyId=' + id
    this.jsonApiService.http('renewal/getCompanyInfo.html', reqdata).subscribe(data => {
      if (data.success) {
        this.companyInfo = data.data
        if (type === 1) {
          this.page.businessType = data.data.businessType
        }
        if (this.synchroParentSelect || changeType) {
          this.page.renewalCycle = data.data.renewalCycle
          this.page.warrantyCycle = data.data.warrantyCycle

          this.page.firstRenewalCycle = data.data.firstRenewalCycle
          this.page.firstWarrantyCycle = data.data.firstWarrantyCycle

          // $("#companyForm").data('bootstrapValidator').resetForm();
          // NOT_VALIDATED：未校验的  VALIDATING：校验中的  INVALID：校验失败的  VALID：校验成功的
          $('#companyForm').bootstrapValidator('updateStatus', 'renewalCycle', 'NOT_VALIDATED')
          $('#companyForm').bootstrapValidator('updateStatus', 'warrantyCycle', 'NOT_VALIDATED')

          $('#companyForm').bootstrapValidator('updateStatus', 'firstRenewalCycle', 'NOT_VALIDATED')
          $('#companyForm').bootstrapValidator('updateStatus', 'firstWarrantyCycle', 'NOT_VALIDATED')
        }
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //from表单提交
  onSubmit() {
    if (this.pageType === 'updata') {
      if (this.page.id == this.page.parentId) {
        this.jsonApiService.message('父级公司不能和公司相同')
        return
      }
      if (this.companyList && this.companyList.length > 0) {
        for (let item of this.companyList) {
          if (item.id == this.page.parentId) {
            if (item.parent == this.page.id) {
              this.jsonApiService.message('父级公司不能是公司的下级')
              return
            }
          }
        }
      }
    }
    if (this.pageType === 'new') {
      $('#companyForm').bootstrapValidator('validate') //开启验证
      let isValid = $('#companyForm').data('bootstrapValidator').isValid() //验证是否通过
      if (isValid) {
        this.updata()
      }
    } else if (this.pageType === 'updata') {
      this.timer = setTimeout(() => {
        $('#companyForm').bootstrapValidator('validate') //开启验证
        let isValid = $('#companyForm').data('bootstrapValidator').isValid() //验证是否通过
        if (isValid) {
          this.updata()
        }
      }, 500)
    }
  }
  telChange() {
    if (!this.page.tel) {
      this.page.tel = ''
    }
  }
  // 校验签单单位是否为必填项(只有父级公司id为空，并且选择的水泥行业，签单单位才是必填项)
  isRequiredForSignUnit() {
    if (!this.page.parentId && this.page.businessType === '01') {
      $('#companyForm').bootstrapValidator('addField', 'signUnit', {
        validators: {
          notEmpty: {
            message: '请输入签单单位'
          }
        }
      })
    } else {
      this.validatorOptions.fields.signUnit.validators = {}
    }
    // $("#companyForm").data('bootstrapValidator').resetForm();
    $('#companyForm').bootstrapValidator('updateStatus', 'signUnit', 'NOT_VALIDATED')
  }
  //from表单提交
  updata() {
    clearTimeout(this.timer)
    if (this.page.parentName === 'ROOT(根目录)') {
      this.page.parentName = ''
    }
    this.page.isEnable = this.isOpenCycle ? 1 : 0 // 是否开启续费周期
    this.page.isSyncRenewal = this.renewChildSelect ? 1 : 0 // 是否同步续费周期子集
    this.page.isSyncwarranty = this.warrantyChildSelect ? 1 : 0 // 是否同步保修周期子集
    // 公司名称去除前后空格
    const params = {
      ...this.page,
      companyName: this.page.companyName.trim()
    }
    let reqdata: string = '',
      url: string = ''
    if (this.pageType === 'new') {
      url = 'company/add.html'
      for (let item in params) {
        if (params[item] || params[item] === 0) {
          if (!reqdata) {
            reqdata += item + '=' + params[item]
          } else {
            reqdata += '&' + item + '=' + params[item]
          }
        }
      }
    } else if (this.pageType === 'updata') {
      url = 'company/edit.html'
      for (let item in params) {
        reqdata += '&' + item + '=' + params[item]
      }
    }
    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      this.router.navigate(['/system/company'], {
        queryParams: {
          nowPage: this.curPage
        }
      })
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/system/company'], {
      queryParams: {
        nowPage: this.curPage
      }
    })
  }
  //拉取省市县数据
  initdata() {
    return new Promise(
      function (resolve, reject) {
        this.jsonApiService.http('company/regionList.html', null).subscribe(data => {
          if (data.message) {
            this.areaData = data.data
            for (let item of this.areaData) {
              if (item.level === 2) {
                this.provinceNameArr.push(item)
              }
            }
            resolve()
          } else {
            this.jsonApiService.message(data.message)
            reject()
          }
        })
      }.bind(this)
    )
  }
  ngOnInit() {
    this.initMap()
    //初始化from表单
    this.initdata().then(() => {
      this.synchroParentSelect = false // 是否同步父级
      this.isOpenCycle = false // 是否开启续费周期
      this.renewChildSelect = false // 是否同步续费周期子集
      this.warrantyChildSelect = false // 是否同步保修周期子集
      if (this.pageType === 'updata') {
        this.page_title = '编辑'
        let reqdata = 'id=' + this.rowId

        this.jsonApiService.http('company/companyInfo.html', reqdata).subscribe(data => {
          if (data.success) {
            for (let item in this.page) {
              this.page[item] = data.data[item]
            }
            if (data.data.isEnable == 1) {
              this.isOpenCycleClick()
            }
            var temCity = data.data.addressEntity
            if (temCity) {
              this.provinceChange(temCity.provinceId == null ? '' : temCity.provinceId)
              this.cityChange(temCity.cityId == null ? '' : temCity.cityId)
              this.page.provinceId = temCity.provinceId == null ? '' : temCity.provinceId
              this.page.cityId = temCity.cityId == null ? '' : temCity.cityId
              this.page.townId = temCity.townId == null ? '' : temCity.townId
            }
            if (!data.data.parentName) {
              this.page.parentName = 'ROOT(根目录)'
            }
            this.loadMarker()
            // 请求公司信息
            this.getCompanyCycle(data.data.parentId, 0)
            this.isRequiredForSignUnit()
          } else {
            this.jsonApiService.message(data.message)
          }
        })
      } else {
        this.isOpenCycleClick()
        return
      }
    })
  }
  // 是否同步
  synchroParentSelectClick() {
    this.synchroParentSelect = !this.synchroParentSelect
    if (this.synchroParentSelect) {
      if (this.page.parentId) {
        // this.getCompanyCycle(this.page.parentId)
        const { renewalCycle, warrantyCycle, firstRenewalCycle, firstWarrantyCycle } = this.companyInfo
        this.page.renewalCycle = renewalCycle
        this.page.warrantyCycle = warrantyCycle

        this.page.firstRenewalCycle = firstRenewalCycle
        this.page.firstWarrantyCycle = firstWarrantyCycle
      } else {
        this.page.renewalCycle = '12'
        this.page.warrantyCycle = '12'
        this.page.firstRenewalCycle = '12'
        this.page.firstWarrantyCycle = '12'
      }
      // $("#companyForm").data('bootstrapValidator').resetForm();
      $('#companyForm').bootstrapValidator('updateStatus', 'renewalCycle', 'NOT_VALIDATED')
      $('#companyForm').bootstrapValidator('updateStatus', 'warrantyCycle', 'NOT_VALIDATED')
    }
  }
  // 是否开启周期设置
  isOpenCycleClick() {
    this.isOpenCycle = !this.isOpenCycle
    if (!this.isOpenCycle) {
      $('#cycle').css('display', 'none')
      $('#renewalCycle').attr('disabled', 'true')
      $('#warrantyCycle').attr('disabled', 'true')
      this.renewChildSelect = false
      this.warrantyChildSelect = false
    } else {
      $('#cycle').css('display', 'block')
      $('#renewalCycle').removeAttr('disabled')
      $('#warrantyCycle').removeAttr('disabled')
    }
  }
  // 是否同步续费周期子集
  renewChildSelectClick() {
    this.renewChildSelect = !this.renewChildSelect
  }
  // 是否同步续费周期子集
  warrantyChildSelectClick() {
    this.warrantyChildSelect = !this.warrantyChildSelect
  }
  isShowMap: boolean = false
  baiduMap: any //地图组件
  // 打开地图
  showMap() {
    // this.isShowMap = true;
    // if(!this.MAP) {
    // 	this.initMap();
    // }else {
    // 	$('#suggestId').val('')
    // 	this.baiduMap = this.MAP;
    // 	if(this.page.lng && this.page.lat){
    // 		this.loadMarker();
    // 	}else {
    // 		setTimeout(() => {
    // 			this.MAP.centerAndZoom(new BMap.Point(116.331398,39.897445), 14);
    // 		}, 200);
    // 	}
    // }
    // $('#suggestId').val('')
    // this.baiduMap = this.MAP
    this.loadMarker()
  }
  // 初始化地图
  MAP: any
  initMap() {
    let that = this
    var map = new BMap.Map('baiduMap', { enableMapClick: false })
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    this.MAP = map
    this.baiduMap = this.MAP
    const point = new BMap.Point(116.404, 39.915) //创建点坐标
    map.centerAndZoom(point, 14) //初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom()
    map.addEventListener('click', function (e) {
      const marker = new BMap.Marker(e.point) // 创建标注
      let circle = new BMap.Circle(e.point, that.page.radius, railStyle) //创建圆
      map.clearOverlays()
      map.addOverlay(marker)
      map.addOverlay(circle)
      const WGS84point = toWGS84({ lng: e.point.lng, lat: e.point.lat })
      that.page.lng = WGS84point.lng
      that.page.lat = WGS84point.lat
    })
    this.initBmapAutoSearch(map)
  }
  // 地图打点-渲染
  loadMarker() {
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    if (this.page.lng && this.page.lat) {
      let point = toMapPoint({ lng: this.page.lng, lat: this.page.lat })
      let mapPoint = new BMap.Point(point.lng, point.lat)
      let circle = new BMap.Circle(mapPoint, this.page.radius, railStyle) //创建圆
      this.MAP.centerAndZoom(mapPoint, 16)
      let marker = new BMap.Marker(point) // 创建标注
      this.MAP.clearOverlays()
      this.MAP.addOverlay(marker)
      this.MAP.addOverlay(circle)
    }
  }
  // 百度地图自动检索功能
  initBmapAutoSearch(map) {
    const that = this
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    //建立一个自动完成的对象
    let autoSearch = new BMap.Autocomplete({ input: 'suggestId', location: map })
    autoSearch.addEventListener('onhighlight', function (e) {
      //鼠标放在下拉列表上的事件
      var str = ''
      var _value = e.fromitem.value
      var value = ''
      if (e.fromitem.index > -1) {
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str = 'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value
      value = ''
      if (e.toitem.index > -1) {
        _value = e.toitem.value
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str += '<br />ToItem<br />index = ' + e.toitem.index + '<br />value = ' + value
      document.getElementById('searchResultPanel').innerHTML = str
    })
    let myValue
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野
    autoSearch.addEventListener(
      'onconfirm',
      function (e) {
        //鼠标点击下拉列表后的事件
        let _value = e.item.value
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business
        document.getElementById('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' + e.item.index + '<br />myValue = ' + myValue
        let local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: function (result) {
            // var pp = result.getPoi(0).point;    //获取第一个智能搜索的结果
            myGeo.getPoint(
              local.getResults().keyword,
              function (point) {
                if (point) {
                  var pointNew = new BMap.Point(point.lng, point.lat)
                  let circle = new BMap.Circle(pointNew, that.page.radius, railStyle) //创建圆
                  map.centerAndZoom(pointNew, 16)
                  map.clearOverlays()
                  map.addOverlay(new BMap.Marker(pointNew))
                  map.addOverlay(circle)
                  // that.page.lng = pointNew.lng;
                  // that.page.lat = pointNew.lat;
                } else {
                  alert('您选择地址没有解析到结果!')
                }
              },
              '北京市'
            )
          }.bind(this)
        })
        local.search(myValue)
      }.bind(this)
    )
  }
  suggestSearchBtn() {
    var that = this
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    if (!$('#suggestId').val()) {
      that.jsonApiService.message('请先输入地址')
      return
    }
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(
      $('#suggestId').val(),
      function (point) {
        if (point) {
          var pointNew = new BMap.Point(point.lng, point.lat)
          let circle = new BMap.Circle(pointNew, that.page.radius, railStyle) //创建圆
          that.MAP.centerAndZoom(pointNew, 16)
          that.MAP.clearOverlays()
          that.MAP.addOverlay(new BMap.Marker(pointNew))
          that.MAP.addOverlay(circle)
        } else {
          alert('您选择地址没有解析到结果!')
        }
      },
      '全国'
    )
  }

  // 查询所选公司的签单单位
  getSignUnit(companyId: string) {
    let params = 'companyId=' + companyId
    this.jsonApiService.http2('company/querySignUnit.html', params).subscribe(data => {
      if (data.success) {
        this.page.signUnit = data.data
      } else {
        this.page.signUnit = ''
      }
    })
  }
  // 查询所选公司的销售归属
  getSaleAscription(companyId: string) {
    let params = 'companyId=' + companyId
    this.jsonApiService.http2('company/querySaleAscription.html', params).subscribe(data => {
      if (data.success) {
        this.page.saleAscription = data.data
      } else {
        this.page.saleAscription = ''
      }
    })
  }
}
